package com.example.onion.hxchat.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.example.onion.hxchat.adapter.MyNotificationAdapter;
import com.example.databean.FriendApplyBean;
import com.example.onion.hxchat.mvvm.WcFriendViewModel;
import com.example.onion.hxchat.room.entity.Friend;
import com.example.onion.hxchat.util.HttpUtils;
import com.example.onion.hxchat.util.MyLocalDatabaseHelper;
import com.example.onion.hxchat.util.PassWordHelp;
import com.example.superyi.mainBar.MainBar;
import com.example.superyi.myteam.R;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.hyphenate.EMContactListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.Request;

/**
 * 显示通知列表的fragment
 * 含version
 */
public class FriendApplyNotificationFragment extends Fragment {

    private View view;
    private RecyclerView mRecyclerView;
    private MyNotificationAdapter myNotificationAdapter;
    private List<FriendApplyBean> mList = new ArrayList<>();
    private MyLocalDatabaseHelper dbHelper;
    private int version = 4;
    private String accountId;
    private WcFriendViewModel friendViewModel;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.friend_apply_notification, container, false);
        accountId = PassWordHelp.readPassword(requireContext())[0];
        dbHelper = new MyLocalDatabaseHelper(getContext(),"local.db",null,version);
        initRecyclerView();
        initData();
        return view;
    }


    private void initData() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from notification",null);
        if (cursor.moveToFirst()){
            do {
                String userId = cursor.getString(cursor.getColumnIndex("userId"));
                String userName = cursor.getString(cursor.getColumnIndex("userName"));
                String applyContent = cursor.getString(cursor.getColumnIndex("applyContent"));
                FriendApplyBean friendApplyBean = new FriendApplyBean(userId,userName,applyContent);
                mList.add(friendApplyBean);
            }while (cursor.moveToNext());
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        friendViewModel = new ViewModelProvider(requireActivity()).get(WcFriendViewModel.class);
    }

    /**
     * TODO 对recycleview进行配置
     */

    private void initRecyclerView() {
        //获取RecyclerView
        mRecyclerView = view.findViewById(R.id.friend_apply_scan_recyclerview_wc);
        //创建adapter
        myNotificationAdapter = new MyNotificationAdapter(mList, getActivity(),friendViewModel);
        myNotificationAdapter.setApplyResultListener(new MyNotificationAdapter.applyResultListener() {
            @Override
            public void acceptApply(FriendApplyBean friendApplyBean) throws HyphenateException {

                String userId = friendApplyBean.getUserId();
                String userName = friendApplyBean.getUserName();
                //环信接受好友请求
                EMClient.getInstance().contactManager().acceptInvitation(userId);
                //接收好友请求，保存数据至本地及服务器
                HttpUtils httpUtils = HttpUtils.getInstance();
                FormBody.Builder builder = new FormBody.Builder();
                builder.add("userId", userId);
                FormBody formBody = builder.build();
                httpUtils.asyncPost("http://49.232.60.155:8080/AppServer_war/GetUserNameByIdServlet", formBody, new HttpUtils.HttpCallBack() {
                    @Override
                    public void onError(Request request, IOException e) {

                    }

                    @SuppressLint("LongLogTag")
                    @Override
                    public void onSuccess(Request request, String result) {
                        Gson gson = new Gson();
//                        JsonObject resultJson = gson.fromJson(result, JsonObject.class);
//                        JsonElement jsonElement = resultJson.get("state");
//                        Log.e("login Result ",resultJson.toString());
//                        if (jsonElement.getAsString().equals("success"))
                        JsonObject resultJson = gson.fromJson(result, JsonObject.class);
                        JsonElement jsonElement = resultJson.get("userName");
                        String userName =jsonElement.getAsString();
                        Friend friend = new Friend(userName,userId,accountId);
                        friendViewModel.insertFriend(friend);
                        Log.e("FriendNotificationFragment","本地保存好友信息成功.");
                    }
                });
//                friendViewModel.insertFriend(new Friend(userId,userId,accountId));
//                SQLiteDatabase db1 = dbHelper.getWritableDatabase();
//                db1.execSQL("insert into friend(userId,userName) values(?,?)",new String[]{userId,userId});
                HttpUtils httpUtils1 = HttpUtils.getInstance();
                FormBody.Builder builder1 = new FormBody.Builder();
                builder1.add("userId",userId);
                builder1.add("userName",userName);
                builder1.add("userOwnerId",accountId);
                builder1.add("userOwnerName",accountId);
                FormBody formBody1 = builder.build();
                httpUtils1.asyncPost("http://49.232.60.155:8080/AppServer_war/StoreFriendServlet", formBody1, new HttpUtils.HttpCallBack() {
                    @Override
                    public void onError(Request request, IOException e) {
                        showToast(requireActivity(),"添加失败，请检查网络问题！");
                    }

                    @Override
                    public void onSuccess(Request request, String result) {
                        Gson gson = new Gson();
                        JsonObject resultJson = gson.fromJson(result, JsonObject.class);
                        JsonElement jsonElement = resultJson.get("state");
                        Log.e("login Result ",resultJson.toString());
                        if (jsonElement.getAsString().equals("success")) {
                            Log.e("FriendNotification", "添加成功");
                            showToast(requireActivity(),"添加成功");
                        } else {
                            showToast(requireActivity(),"添加失败，已存在好友信息或网络问题！");
                            Log.e("FriendNotification", "添加失败");
                        }
                    }
                });
            }

            @Override
            public void rejecttApply(FriendApplyBean friendApplyBean) throws HyphenateException {
                String userId = friendApplyBean.getUserId();
                //环信拒绝好友请求
                EMClient.getInstance().contactManager().declineInvitation(userId);
            }
        });

        //给RecyclerView设置adapter
        mRecyclerView.setAdapter(myNotificationAdapter);
        //设置layoutManager,可以设置显示效果，是线性布局、grid布局，还是瀑布流布局
        //参数是：上下文、列表方向（横向还是纵向）、是否倒叙
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        //设置item的分割线
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));

    }

    /**
     * 显示toast
     * @param ctx
     * @param msg
     */
    public static void showToast(final Activity ctx, final String msg) {
        // 判断是在子线程，还是主线程
        if ("main".equals(Thread.currentThread().getName())) {
            Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
        } else {
            // 子线程
            ctx.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
                }
            });
        }
    }
    private void listenFriendStatus()
    {
        EMClient.getInstance().contactManager().setContactListener(new EMContactListener() {


            @Override
            public void onContactInvited(String username, String reason) {
                //收到好友邀请
            }

            @Override
            public void onFriendRequestAccepted(String s) {
                //好友请求被同意
            }

            @Override
            public void onFriendRequestDeclined(String s) {
                //好友请求被拒绝
            }

            @Override
            public void onContactDeleted(String username) {
                //被删除时回调此方法
            }


            @Override
            public void onContactAdded(String username) {
                //增加了联系人时回调此方法
            }
        });
    }
}
